package com.os.meituan.service.sec;

import com.os.meituan.common.StringClass;
import com.os.meituan.model.pomodel.T_SYS_Role;
import com.os.meituan.repository.SYS_RoleRepository;
import com.os.meituan.repository.SYS_Role_To_UserRepository;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;


@Service
public class SYS_RoleService {
    @Resource
    private SYS_Role_To_UserRepository sys_role_to_userRepository;
    @Resource
    private SYS_RoleRepository sys_roleRepository;
    public List<String> getEnableRolesKeysByUserId(String userId) {
        List<T_SYS_Role> list = getEnableRolesByUserId(userId);
        return list.stream().map(q -> q.getRoleKey()).collect(toList());
    }
    public List<T_SYS_Role> getEnableRolesByUserId(String userId) {
        List<T_SYS_Role> listRoles = getRolesByUserId(userId);

        return listRoles.stream().filter(q -> q.getEnable() == 1).collect(Collectors.toList());
    }
    public List<T_SYS_Role> getRolesByUserId(String userId) {
        var listR_T_U = sys_role_to_userRepository.findUserRoleIds(userId);
        List<T_SYS_Role> listRoles = sys_roleRepository.findByIdIn(listR_T_U);

        return listRoles;
    }

    public List<String> getEnableRolesPowerListByUserId(String userId) {
        List<T_SYS_Role> list = getEnableRolesByUserId(userId);
        List<String> powerList = new ArrayList<>();
        list.forEach(q -> powerList.addAll(Arrays.asList(q.getPower().split(","))));

        return powerList.stream().distinct().collect(toList());
    }

    public List<String> getRolePowerByRoleKey(String key) {
        T_SYS_Role rInfo = getModelByKey(key);
        if (rInfo == null) {
            return null;
        }
        return rInfo.getPower() == null ? null : Arrays.asList(rInfo.getPower().split(","));
    }
    public T_SYS_Role getModelByKey(String key) {

        if (StringClass.isBlank(key)) {
            return null;
        }

        return sys_roleRepository.findByRoleKey(key);
    }

}
